<template>
  <div class="box">
    <div class="haeder">
      <div class="heart">
        <span></span>
        <span>新增添加菜单</span>
        <span @click="exit">返回上一页</span>
      </div>
      <div>菜品类目</div>
      <el-select v-model="catevalue" placeholder="请选择输入菜品类目">
        <el-option v-for="item in category" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <div>菜品名称</div>
      <el-input v-model="name" type="txt" placeholder="请输入菜品名称" :clearable="true">
      </el-input>
      <div>菜品价格</div>
      <el-input v-model="price" min="0" type="number" placeholder="请输入菜品价格" :clearable="true">
      </el-input>
      <!-- 菜品单位 -->
      <!-- default-first-option:在输入框按下回车，选择第一个匹配项。需配合 filterable 或 remote 使用 -->
      <!-- filterable:是否可搜索 -->
      <!-- allow-create:是否允许用户创建新条目，需配合 filterable 使用 -->
      <el-select v-model="compvalue" :default-first-option="true" :filterable="true" :allow-create="true"
        placeholder="请选择或输入菜品单位">
        <el-option v-for="item in company" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <div>菜品图片</div>
      <el-upload :action="action" list-type="picture-card" name="file" accept=".jpg,.png,.webp,.jfif,.jpeg" :limit="1"
        :on-remove="bannerRemove" :on-success="bannerSuccess" :on-preview="handlepreview" :before-upload="project"
        :file-list="goodsimage" :multiple="false" :on-error="onErr">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync='dialogVisible'>
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
      <div class="submit">
      <el-button type="success" size="medium" @click="bIn(but)">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      category: [], // 菜品类目
      company: [], // 菜单单位
      action: this.URL.m().uploadres, // 头像上传接口
      catevalue: "", // 选中产品类目
      name: "", //菜品名称
      price: "",
      compvalue: "", // 选中菜品单位
      goodsimage: [], // 商品图片
      unit: '', // 自定义的单位
      but: '上架菜品',
      // 图片展开大图
      dialogImageUrl: '',
      dialogVisible: false,
      pagenum: 0,
      custom: false,
      id: '', // 该条数据的id，用于编辑
      loading: true,
    };
  },
  methods: {
     // 路由跳转
     exit(){
      // console.log(this.$router,'rouer');
      this.$router.push({ name: "Store" })
    },
    // 上传图片展开大图
    handlepreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传失败
    onErr(e) {
      this.$message.error('上传失败，请重新上传' + e)
    },
    // 上传时
    project(file) {
      console.log('上传中' + file);
    },
    // 删除图片
    bannerRemove() {
      this.goodsimage = []
      this.Message_Box.MessageSuccess('删除成功');
    },
    // 上传成功 ：封面图
    bannerSuccess(res, file, fileList) {
      this.goodsimage.push({ url: res.data, uid: file.uid })
      console.log(fileList);
      console.log(this.action,'action');
    },
    // 获取菜品类目和单位
    async obtaincate() {
      // 菜品类目信息获取
      let dishesres = await new this.request(this.URL.m().dishesacquire + "?page=0").GET();
      // 获取菜品单位
      let obtainres = await new this.request(this.URL.m().acquireunit + "?page=0").GET();
      // 必须同时获取
      Promise.all([dishesres, obtainres])
        .then(res => {
          this.category = res[0].data.data.result;
          this.company = res[1].data.data.result;// 获取菜品单位
          console.log(this.company);
        }).catch(err => {
          this.Message_Box.MessageError('菜品类目或单位获取失败' + err);
        });
    },
    // 上传菜品
    bIn(is) {
      let cate = this.category.filter((item) => {
        return item.value == this.catevalue;
      });
      let category = cate.length == 0 ? "" : cate[0].cid;
      const obj = {
        _id: this.id, // 该条数据的id，用于编辑
        category: this.catevalue, // 选中的菜品类目
        name: this.name, //菜品名称
        unitprice: this.price, // 商品单价
        unit: this.compvalue, // 选中菜品单位
        image: JSON.stringify(this.goodsimage),
        cid: category, // 改分类下的cid
      };
      if (is == "上架菜品") {
        this.purequest(obj, is, this.URL.m().uploaddishes);
      } else {
        // 提交修改
        this.purequest(obj, is, this.URL.m().modifydishes);
      }
    },
    // 提交或者修改公用请求
    async purequest(obj, is, url) {
      // 是否完成
      try {
        let res = await new this.request(url, JSON.stringify(obj)).POST();
        if (res.status !== 200) {
          //失败
          this.Message_Box.MessageError(res.data.msg);
        } else {
          // 成功
          this.Message_Box.MessageSuccess(res.data.msg);
          this.$router.push({ name: "menus" });
        }
      } catch (e) {
        this.Message_Box.MessageError("请求失败，程序错误");
      }
    },

    // 提交或者修改公用请求
    // async dishunit() {
    //   //
    //   let obj = { unit: this.unit };
    //   try {
    //     let res = await new this.request(
    //       this.URL.m().dishunit,
    //       JSON.stringify(obj)
    //     ).POST();
    //     if (res.status !== 200) {
    //       //失败
    //       this.Message_Box.MessageError(res.data.msg);
    //     } else {
    //       // 成功
    //       this.Message_Box.MessageSuccess(res.data.msg);
    //       this.compvalue = "";
    //       this.unit = "";
    //       this.obtaincate();
    //     }
    //       } catch (e) {
    //         this.Message_Box.MessageError("请求失败，程序错误");
    //       }
    //     },
  },
  created() {
    const loading = this.$loading({
      lock: true,
      text: '正在拼命加载中...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    let res = this.$route.params
    this.obtaincate()
    // 编辑传来数据
    if (JSON.stringify(res) != "{}") {
      this.but = '修改提交',
        this.id = res.item._id,
        this.catevalue = res.item.category,
        this.name = res.item.name,
        this.price = res.item.unitprice,
        this.compvalue = res.item.unit,
        this.goodsimage = res.item.image
    }
    loading.close()
  },
};
</script>

<style lang="less" scoped>
.box {

  padding: 0 140px 0;
  width: 100%;
  height: 100%;
  background-color: #f6f8f9;
}
.haeder {
  width: 1000px;
  height: 100%;
  padding: 10px 90px;
  background-color: #ffffff;
}
.heart {
  display: flex;
  justify-content: space-between;
}
.heart span{
  font-weight: 600;
  font-size: 18px;
}
.heart span:nth-child(2){
  margin-top: 15px;
  font-size: 25px;
}
.heart span:nth-child(3){
  cursor: pointer;
}
.haeder div{
  margin: 10px 0;
}
.submit{
  text-align: center;
}
</style>